<?php
namespace app\helpers\base;
/**
 * 图片验证码.
 */
use Yii;

class ImageVcode{

    const MC_KEY_PRE = 'Image_Verify_Code_Key_';
    const MC_KEY_VERIFY_COUNT_PRE = 'Image_Verify_Code_Count_';

    /**
     * 取图片验证码.
     */
    public static function getImageVerify($identity, $type='gif'){
        Image::buildImageVerify(5, 1, $type);
        $vcode = Image::getVcode();

        $redis = Yii::$app->redis;
        $redis->set(self::MC_KEY_PRE.$identity,$vcode);
        $redis->expire(self::MC_KEY_PRE.$identity,60*5);
        $redis->set(self::MC_KEY_VERIFY_COUNT_PRE.$identity, 0); //计数器
        $redis->expire(self::MC_KEY_VERIFY_COUNT_PRE.$identity,60*5);
    }

    /**
     * 取图片验证码.
     */
    public static function getImageVerify2($identity, $type='gif'){
        
        $img = new Captcha();
        $str = $img->getTypes('DIG');
        $strlen = strlen($str);
        $word_list = str_split($str,1);
        $len = 4;
        $word = '';
        for($i=0;$i<$len;$i++)
        {
            $word .=$word_list[mt_rand(0,$strlen-1)];
        }

        /*
        $mcHandler = MemcachedClient::GetInstance('default');
        $mcHandler->set(self::MC_KEY_PRE.$identity, md5($word), 60*5);
        $mcHandler->set(self::MC_KEY_VERIFY_COUNT_PRE.$identity, 0, 60*5); //计数器
        */

        $img->addDefaultText($word);
        $img->addLine();
        $img->output();
    }

    /**
     * 验证图片验证码.
     */
    public static function verifyCode($identity, $vcode){
        $st = false;

        $redis = Yii::$app->redis;
        $val = $redis->get(self::MC_KEY_PRE.$identity);
        $count = $redis->incr(self::MC_KEY_VERIFY_COUNT_PRE.$identity);
        if ($val && $count <= 5){ //二维码存在&&验证次数小于5次
            $st = $val==md5($vcode)? true: false;
            if ($st){
                $redis->del(self::MC_KEY_PRE.$identity);
            }
        } else {
            $redis->del(self::MC_KEY_PRE.$identity);
        }

        return $st;
    }
}